import { ref, onUnmounted } from 'vue';

export function useWebSocket(userId, talkerId, url) {
    const socket = ref(null);
    const isConnected = ref(false);
    const messages = ref([]);
    
    // 连接WebSocket
    const connect = () => {
        socket.value = new WebSocket(url);
        
        // 连接成功
        socket.value.onopen = () => {
            console.log('WebSocket连接成功');
            isConnected.value = true;
        };
        
        // 接收消息
        socket.value.onmessage = (event) => {
            try {
                console.log('接收到消息:', event.data);
                const jsonMsg = JSON.parse(event.data); // 解析JSON格式的消息，转换为js对象
                messages.value.push(jsonMsg);
            } catch (error) {
                console.error('发送错误:', error);
            }
            // 可以在这里分发事件或更新UI
        };

        // 连接关闭
        socket.value.onclose = (event) => {
            console.log('WebSocket连接关闭:', event);
            isConnected.value = false;
        };
        
        // 错误处理
        socket.value.onerror = (error) => {
            console.error('WebSocket错误:', error);
            isConnected.value = false;
        };
    };
    
    // 发送消息（必须发送字符串格式）
    const sendMessage = (message : string) => {
        if (socket.value?.readyState === WebSocket.OPEN) {
            socket.value.send(message);
            console.log('发送消息:', message);
        }
    };

    // 发送私聊消息（传入一个消息对象）
    const sendPrivate = (msgObj : Object) => {
        messages.value.push(msgObj);
        sendMessage(JSON.stringify(msgObj));
    };
    
    // 关闭WebSocket
    const close = () => {
        if (socket.value) {
            socket.value.close();
        }
    };
    
    // 组件卸载时清理
    onUnmounted(() => {
        close();
    });
    
    // 初始连接
    connect();
    
    return {
        socket,
        isConnected,
        messages,
        sendPrivate,
        close,
        connect
    };
}